﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.IO;

using Jzy.Model.Mail;

using Frame.Lib.Core.Attach;
using Frame.Lib.Common;
using Frame.Lib.Enums;
using Jzy.DAL;

namespace Jzy.BLL.Mail
{
    public class SMTPClient
    {
        private int _userID;

        public SMTPClient(int userID)
        {
            _userID = userID;
        }

        internal void Send(WebMailAccountInfo accountInfo,WebMailInfo mailInfo, System.Web.HttpFileCollection files,IEnumerable<AttachInfo> forwordAttachs)
        {
            SmtpClient client = new SmtpClient(accountInfo.SmtpServer, accountInfo.SmtpPort);
            client.Credentials = new NetworkCredential(accountInfo.SmtpUser, accountInfo.SmtpPwd);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;

            //MailAddress from = new MailAddress("168jzy@163.com", "蒋志勇");
            //MailAddress to = new MailAddress("auqfncel@pub.nt.jsinfo.net", "陈丽");

            MailMessage mail = new MailMessage();
            mail.Subject = mailInfo.Name;
            mail.Body = mailInfo.Body;
            mail.IsBodyHtml = true;
            mail.From = new MailAddress(mailInfo.FromAddr, mailInfo.FromName);

            string[] toAddrs = mailInfo.ToAddr.Split(',');
            foreach (string addr in toAddrs)
            {
                if (addr != "")
                {
                    mail.To.Add(new MailAddress(addr, null));
                }
            }
            string[] ccAddrs = mailInfo.CCAddr.Split(',');
            foreach (string addr in ccAddrs)
            {
                if (addr != "")
                {
                    mail.CC.Add(new MailAddress(addr, null));
                }
            }

            for (int i = 0; i < files.Count; i++)
            {
                if (files[i].FileName != "")
                {
                    files[i].InputStream.Position = 0;
                    Attachment attach = new Attachment(files[i].InputStream, Path.GetFileName(files[i].FileName));
                    
                    mail.Attachments.Add(attach);
                }
            }
            foreach (AttachInfo info in forwordAttachs)
            {
                string filePath = AppSetting.AttachPath + OTableName.WebMailAttach + "\\" + info.Path;

                if (File.Exists(filePath))
                {
                    //FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    
                    //MemoryStream ms = new MemoryStream(
                    Attachment attach = new Attachment(filePath, "");
                    mail.Attachments.Add(attach);
                }
            }

            client.Send(mail);
        }

      
    }
}
